#### load the data


library (tidyverse)
library (ggplot2)
library(jtools)
library (officer)
library (flextable)
library (broom.mixed)
library (car)
library(dplyr)
library (ggplot2)
library (ggeffects)
library(cowplot)
library (psych)
library(readr)
library(lmtest)
library(sandwich)
library (psych)
library(MASS)        
library(sandwich)    
library(lmtest)  

df_clean <- na.omit(data)

# Convert variables to factors 
df_clean$social_media_binary <- as.factor(df_clean$social_media_binary)
df_clean$express_binary <- as.factor(df_clean$express_binary)
df_clean$gender <- as.factor(df_clean$gender)
df_clean$employed <- as.factor(df_clean$employed)
df_clean$education <- as.factor(df_clean$education)
df_clean$urban <- as.factor(df_clean$urban)
df_clean$country_name <- as.factor(df_clean$country_name)
df_clean$wave <- as.factor(df_clean$wave)


# ordered factors
for (item in trust_items) {
  df_clean[[item]] <- factor(df_clean[[item]], levels = c(1, 2, 3, 4), ordered = TRUE)
}


item_models_ordlogit <- list()
item_clustered_ordlogit <- list()


for (item in trust_items) {
  formula <- as.formula(paste(item, "~ social_media_binary + express_binary + age + gender +
                               employed + education + income + urban + country_name + wave"))
  
  model <- polr(formula, data = df_clean, method = "logistic", Hess = TRUE)
  
  clustered <- coeftest(model, vcov = vcovCL(model, cluster = ~country_name))
  

  item_models_ordlogit[[item]] <- model
  item_clustered_ordlogit[[item]] <- clustered
}


# table output
names(item_models_ordlogit) <- c("Executive", "Courts", "National", "Parties", "Parliament", "Military", "Police", "Local")


clustered_vcovs_ordlogit <- lapply(item_models_ordlogit, function(m) vcovCL(m, cluster = ~country_name))
names(clustered_vcovs_ordlogit) <- names(item_models_ordlogit)

# table
modelsummary(
  item_models_ordlogit,
  vcov = clustered_vcovs_ordlogit,
  coef_map = custom_labels,
  stars = TRUE,
  gof_omit = "AIC|BIC|Log|F|Adj|Deviance|Sigma",
  output = "trust_items.docx"  # or "latex", "word", "html"
)













